import React from 'react'
import { Link } from 'react-router-dom'
import { Toast,Grid, Button, Modal } from 'antd-mobile-v2'
import { BASE_URL } from '../../utils/url'
import styles from './index.module.css'
import './profile.scss'
import pic1 from "./mouren1.png";//默认头像
import withHook from "../../utils/Withhook"
import { API } from '../../utils/api'
// 菜单数据
const menus = [
    { id: 1, name: '我的收藏', iconfont: 'icon-coll'},
    { id: 2, name: '我的出租', iconfont: 'icon-ind', to: '/rent'},
    { id: 3, name: '看房记录', iconfont: 'icon-record' },
    {
      id: 4,
      name: '成为房主',
      iconfont: 'icon-identity'
    },
    { id: 5, name: '个人资料', iconfont: 'icon-myinfo' },
    { id: 6, name: '联系我们', iconfont: 'icon-cust' }
  ]

// 默认头像
const DEFAULT_AVATAR=pic1
//class 类组件 个人中心组件
class Myprofile extends React.Component{


    state={
        isLogin:!!localStorage.getItem("my_token"),//判断是否登录（有登录my_token有值），islogin=0表示登录
        userinfo:{
          avatar:"",//头像
          nickname:""}//用户名称
        }

    async getuserinfo(){
    let {isLogin}=this.state
    if(!isLogin){
        Toast.info('请先登录....',1)
    }else{
        let res =await API.get(`/user`)
        if(res.data.status === 200){
        this.setState({
            userinfo:res.data.body
        })
        }else{
          //此时token由于前后端分离项目一关闭，或者后端自动设置，就容易残生token过期
        Toast.info("token已过期,请重新登录...")
        this.setState({
          isLogin: false
        })
        }
    }
    }

  //退出登录点击
  logout=()=>{
    Modal.alert('退出', '你确定要退出吗?', [
       { text: '取消'},
      {
        text: '退出',
        onPress: async () => {
          // 调用退出接口
          await API.post('/user/logout')
          // 移除本地token
          localStorage.removeItem("my_token")
          // 处理状态
          this.setState({
            isLogin: false,
            userInfo: {
              avatar: '',
              nickname: ''
            }
          })
        }
      }
     ])
   }
   //渲染函数：判断登录与否，去渲染个人资料板块
  loginauth=()=>{
  if(!!localStorage.getItem("my_token"))
  {
  return(
      <>
      <div className={styles.auth}>
      <span 
      onClick={this.logout}
      >退出</span>
      </div>
      <div className={styles.edit}>
      编辑个人资料
      <span className={styles.arrow}>
          <i className="iconfont icon-arrow" />
      </span>
      </div>
  </> )}else{
  return (
      <div className={styles.edit}>
      <Button
      type="primary"
      size="small"
      inline
      onClick={() => 
        this.props.to('/login')}>
      去登录
      </Button>
  </div>
  )} }

  //初始化先判断有无token
  componentDidMount(){
      this.getuserinfo()
      }

  
  render() {
  let { nickname , avatar} = this.state.userinfo
  return (
    <div className={styles.root}>
      {/* 个人信息 */}
      <div className={styles.title}>
        <img
          className={styles.bg}
          src={BASE_URL + '/img/profile/bg.png'}
          alt="背景图"
        />
        <div className={styles.info}>
        {/* 头像 */}
          <div className={styles.myIcon}>
            <img className={styles.avatar} src={avatar?BASE_URL+avatar:DEFAULT_AVATAR} alt="icon" />
          </div>
        {/* 用户名 */}
          <div className={styles.user}>
            <div className={styles.name}>{nickname==="" ? "游客，您好！" :nickname}</div>
            {this.loginauth()}
          </div>
        </div>
      </div>

      {/* 九宫格菜单 */}
      <Grid
        data={menus}
        columnNum={3}
        hasLine={false}
        renderItem={item =>
          item.to ? (
            //目前暂无跳转链接
            <Link to={item.to}>
              <div className={styles.menuItem}>
                <i className={`iconfont ${item.iconfont}`} />
                <span>{item.name}</span>
              </div>
            </Link>
          ) : (
            <div className={styles.menuItem}>
              <i className={`iconfont ${item.iconfont}`} />
              <span>{item.name}</span>
            </div>
          )
        }
      />

    </div>
  )
}
}

const Myprofile_2 =withHook(Myprofile) 
export default Myprofile_2